const http = require('http');
const fs = require('fs');
const path = require('path');

const PORT = 8081;
const USERS_FILE = path.join(__dirname, 'data.json');

const server = http.createServer((req, res) => {
  if (req.method === 'POST' && req.url === '/login') {
    let body = '';
    req.on('data', chunk => body += chunk);
    req.on('end', () => {
      try {
        const { username, password } = JSON.parse(body);
        const usersData = JSON.parse(fs.readFileSync(USERS_FILE, 'utf8'));
        const user = usersData.users[username];
        
        if (user && user.password === password) {
          res.writeHead(200, { 'Content-Type': 'text/plain' });
          res.end('登录成功');
        } else {
          res.writeHead(401, { 'Content-Type': 'text/plain' });
          res.end('用户名或密码不正确');
        }
      } catch (err) {
        res.writeHead(400, { 'Content-Type': 'text/plain' });
        res.end('请求格式错误');
      }
    });
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not Found');
  }
});

server.listen(PORT, () => {
  console.log("登录服务器运行在 http://localhost:" + PORT);
});